const video = document.getElementById('video') as HTMLVideoElement

const playBtn = document.getElementById('play') as HTMLButtonElement
const stopBtn = document.getElementById('stop') as HTMLButtonElement
const progress = document.getElementById('progress') as HTMLInputElement
const timestamp = document.getElementById('timestamp') as HTMLSpanElement

// Progress status
let isProgressHoldOn = false

// Play or pause video
function toggleVideoStatus() {
  if (video.paused) {
    video.play()
  } else {
    video.pause()
  }
}

// Update play/pause icon
function updatePlayIcon() {
  if (video.paused) {
    playBtn.innerHTML = '<i class="fa fa-play fa-2x"></i>'
  } else {
    playBtn.innerHTML = '<i class="fa fa-pause fa-2x"></i>'
  }
}

// Stop video
function stopVideo() {
  video.currentTime = 0
  video.pause()
}

// Update progress and timestamp
function updateProgress() {
  const currentTime = video.currentTime
  
  if (!isProgressHoldOn) {
    progress.value = String((currentTime / video.duration) * 100)
  }

  let m: number | string = Math.floor(currentTime / 60)
  m = m < 10 ? '0' + m : m
  let s: number | string = Math.floor(currentTime % 60)
  s = s < 10 ? '0' + s : s

  timestamp.innerHTML = m + ':' + s
}

// Set video time to prrogress
function setVideoProgress() {
  isProgressHoldOn = true
  video.pause()
  video.currentTime = (Number(progress.value) * video.duration) / 100
}
function setProgressStatus() {
  isProgressHoldOn = false
  video.play()
}

// Add event listeners
video.addEventListener('click', toggleVideoStatus)
video.addEventListener('play', updatePlayIcon)
video.addEventListener('pause', updatePlayIcon)
video.addEventListener('timeupdate', updateProgress)

playBtn.addEventListener('click', toggleVideoStatus)
stopBtn.addEventListener('click', stopVideo)

progress.addEventListener('input', setVideoProgress) // hold 时
progress.addEventListener('change', setProgressStatus) // 释放鼠标时
